package com.weixin.app;

import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

public class BasePage {
    AndroidDriver driver;
    By currentBy;
    WebElement webElement;

    public BasePage(AndroidDriver driver) {
        this.driver = driver;
    }

    public WebElement find(String element, String selector) throws Exception {
        By by;
        if(element.equals("id")){
            by = By.id(selector);
        }else if(element.equals("css")){
            by = By.cssSelector(selector);
        }else if(element.equals("xpath")){
            by = By.xpath(selector);
        }else{
            throw new Exception("unknow "+element);
        }
        currentBy = by;
        webElement = driver.findElement(currentBy);
        return webElement;
    }


    public void click() throws Exception {
        try {
            webElement.click();
        }catch (Exception e){
            handleExceptions();
            click();
        }

    }

    public void sendKeys( String str) throws Exception {
        try {
            webElement.sendKeys(str);
        }catch (Exception e){
            handleExceptions();
            sendKeys(str);
        }

    }

    public String getText() throws Exception {
        String elementText = null;
        try {
            elementText = webElement.getText();
        } catch (Exception e) {
            getText();
        }
        return elementText;
    }

    public void handleExceptions(){
        //todo: 解决弹框和各种异常
        //异常类型
        //1. 行为异常，重试机制可也解决
        //2. po实现，重试机制通常效果不大
        //3. 全流程与环境异常 直接fail并自动启动下次执行
    }
}
